#!/bin/bash
set -e

echo "🧪 全栈测试开始..."

# 创建日志目录
mkdir -p logs

# 1. 启动后端
echo "🔧 启动后端服务..."
cd backend
npm start > ../logs/backend.log 2>&1 &
BACKEND_PID=$!
echo "后端 PID: $BACKEND_PID"

# 2. 等待后端就绪
echo "⏳ 等待后端启动..."
timeout 30 bash -c 'until curl -s http://localhost:3001/api/health > /dev/null 2>&1; do sleep 2; done' || {
    echo "❌ 后端启动失败，检查日志: logs/backend.log"
    kill $BACKEND_PID 2>/dev/null || true
    exit 1
}

# 3. 启动前端
echo "🎨 启动前端服务..."
cd ../frontend
./scripts/dev-start-safe.sh > ../logs/frontend.log 2>&1 &
FRONTEND_PID=$!

# 4. 等待前端就绪
echo "⏳ 等待前端启动..."
timeout 60 bash -c 'until curl -s http://localhost:8001 > /dev/null 2>&1; do sleep 2; done' || {
    echo "❌ 前端启动失败，检查日志: logs/frontend.log"
    kill $FRONTEND_PID $BACKEND_PID 2>/dev/null || true
    exit 1
}

echo "✅ 全栈服务已启动"
echo "🌐 前端: http://localhost:8001"
echo "🔧 后端: http://localhost:3001"
echo "📝 前端 PID: $FRONTEND_PID"
echo "📝 后端 PID: $BACKEND_PID"

# 保存 PID 以便后续清理
echo $FRONTEND_PID > logs/frontend.pid
echo $BACKEND_PID > logs/backend.pid

echo "🛑 使用 './scripts/stop-all-services.sh' 停止所有服务"